﻿#include "PoundListPrint.h"
#include <QtWidgets/QApplication>
#include <QDir>
#include "qtsingleapplication.h"
#include <Windows.h>
#include <DbgHelp.h>
#include <QProcess>

/*加入异常报错dump文件*/
#pragma comment(lib,"Dbghelp.lib")
long __stdcall CrashInfocallback(_EXCEPTION_POINTERS* pexcp)
{
	//创建崩溃文件文件夹
	QString sFontTypePath = QCoreApplication::applicationDirPath();     //根目录
	sFontTypePath = sFontTypePath + "/ErrorDump/";

	QDir dir(sFontTypePath);
	if (!dir.exists())
	{
		dir.mkpath(".");
	}

	QString sDumpFileName = sFontTypePath + "/" + QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
	sDumpFileName.append(".dmp");
	std::wstring wstr = sDumpFileName.toStdWString();
	LPWSTR lpwstr = (LPWSTR)wstr.c_str();

	//ADDMSGEX("程序退出", enSysError, FL, QColor(255, 0, 0), _Q(QString("程序异常退出")));

	// 创建dmp文件
	HANDLE hDumpFile = ::CreateFile(
		lpwstr,
		GENERIC_WRITE,
		0,
		NULL,
		CREATE_ALWAYS,
		FILE_ATTRIBUTE_NORMAL,
		NULL
	);

	if (hDumpFile != INVALID_HANDLE_VALUE)
	{
		// dmp文件信息
		MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
		dumpInfo.ExceptionPointers = pexcp;
		dumpInfo.ThreadId = GetCurrentThreadId();
		dumpInfo.ClientPointers = TRUE;

		// 写入dmp文件内容
		::MiniDumpWriteDump(
			GetCurrentProcess(),
			GetCurrentProcessId(),
			hDumpFile,
			MiniDumpNormal,
			&dumpInfo,
			NULL,
			NULL
		);
	}
	return 0;
}

int main(int argc, char *argv[])
{
	//崩溃生成dump文件
	::SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)CrashInfocallback);

	QtSingleApplication a("PoundListPrint", argc, argv);
	if (a.isRunning())  //判断实例是否已经运行
	{
		//QMessageBox::information(nullptr, "提示", "程序已运行！", QMessageBox::Ok);
		a.sendMessage("raise_window_noop", 3000); //4s后激活前个实例
		return EXIT_SUCCESS;
	}

    PoundListPrint w;
    w.show();

	//重复点击程序激活显示
	a.setActivationWindow(&w, true);

	// 启用退出锁定
	QCoreApplication::setQuitLockEnabled(true);
	// 在应用程序退出时终止后台进程 防止关不掉 windows使用
	QObject::connect(&a, &QCoreApplication::aboutToQuit, []()
	{
		QProcess::startDetached("taskkill /F /IM PoundListPrint.exe");
	});

    return a.exec();
}
